<template>
    <div
        ref="chartRef"
        style="width: 100%; height: 160px; margin-top: 10px"
    ></div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import { formatTempData } from "@/utils/format";
import useWeatherData from "@/utils/useWeather";

const { getFutureWeather, city } = useWeatherData();
const chartRef = ref(null);
const futureWeather = ref([]);
const weatherData = ref([]);

/**
 * 根据路由获取近期天气数据
 * 白天，晚上两种温度数据,数据是今天明天后天大后天的温度数据
 * @returns {Promise} 当前城市
 */
onMounted(async () => {
    futureWeather.value = await getFutureWeather();
    weatherData.value = formatTempData(futureWeather.value);
    renderChart(weatherData.value);
});

/**
 * 渲染折线图
 * @param {Array} data 数据
 */
const renderChart = (data) => {
    const chart = echarts.init(chartRef.value);
    chart.setOption({
        // 不显示x,y轴
        xAxis: {
            type: "category",
            boundaryGap: false,
            show: false,
            data: data.map((item) => item.日期),
        },
        yAxis: {
            type: "value",
            show: false,
            interval: 3,
        },
        grid: {
            top: "15%",
            left: "7%",
            right: "7%",
            bottom: "0%",
            containLabel: true,
        },
        // 两组折线图：白天和晚上
        series: [
            {
                type: "line",
                data: data.map((item) => item.白天),
                smooth: true,
                lineStyle: {
                    color: "#516ec2",
                },
                label: {
                    show: true,
                    position: "top",
                    formatter: "白{c}°C",
                    color: "#fff",
                },
            },
            {
                type: "line",
                data: data.map((item) => item.晚上),
                smooth: true,
                lineStyle: {
                    color: "#91cc75",
                },
                // 标签在折线的下方
                label: {
                    show: true,
                    position: "top",
                    formatter: "夜{c}°C",
                    color: "#fff",
                    position: "bottom",
                },
            },
        ],
    });
};
</script>
<style scoped></style>
